import { createApp, h, reactive, render } from 'vue'
import { Grid } from '@qif/h5-player'
import '@qif/h5-player/lib/style.css'
import { splitStyles } from './SplitEunm'

class QifPlayer {
  constructor(
    id, // 播放容器的id
    winNum, // 分屏窗口数，支持 1，4，6，8，9，16 窗口
    ip, // 视频服务对外 IP, 默认协议头用'http://'，如需要指定 https:// 协议 头,传入 https:// + ip
    port, // 视频服务对外端口
    token, // 用户登陆 token 信息
    playMethod, // 1:实时视频，2:录像回放
    onEventNotify, // 回调方法名称
    isVideoFull, // true:视频铺满所在播放 video 标签窗口 false:视频自适应所在的 video
    ak, // ak 值
  ) {
    this.player = null
    this.id = id
    this.winNum = winNum
    this.ip = ip
    this.port = port
    this.mainPort = '8811'
    this.token = token
    this.playMethod = playMethod
    this.onEventNotify = onEventNotify
    this.isVideoFull = isVideoFull
    this.ak = ak

    this.gridStyle = reactive({})

    this.setNode(this.id)
    this.setWinNum(this.winNum)

    // 添加键盘事件监听器
    document.addEventListener('keydown', (event) => {
      // 检查按下的键是否是 ESC 键的键码
      if (event.key === 'Escape' || event.key === 'Esc')
        this.exitScreen()
    })
  }

  createVNode () {
    const saveComponentInstance = (instance) => {
      this.player = instance
    }
    return () => (
      <Grid ref={saveComponentInstance} protocol="ws" ip={this.ip} port={this.port} mainPort={this.mainPort} grid-log onOnEventNotify={this.onEventNotify} gridStyle={this.gridStyle}></Grid>
    )
  }

  setNode (id) {
    const dom = document.getElementById(id)
    // eslint-disable-next-line ts/no-this-alias
    const that = this
    if (dom) {
      const app = createApp({
        render () {
          const dynamicComponentVNode = h(that.createVNode())
          render(dynamicComponentVNode, dom)
        },
      })

      if (app._container) {
        // 如果已经挂载，尝试卸载
        app.unmount()
      }
      app.mount(dom)
    }
  }

  // 设置窗口数
  setWinNum (winNum) {
    this.gridStyle.display = 'grid'
    this.gridStyle.gridGap = '2px'
    this.gridStyle['grid-template-rows'] = splitStyles[winNum]['grid-template-rows']
    this.gridStyle['grid-template-columns'] = splitStyles[winNum]['grid-template-columns']
    this.player?.setSplitScreen(winNum)
  }

  // 开启自动更新token
  openRefreshToken (ak, sk) {
    this.ak = ak
    decodeURIComponent(escape(atob(sk)))
  }

  // 设置token
  setToken (token) {
    this.token = token
  }

  // 销毁窗口
  destory () {
    document.getElementById(this.id).remove()
    this.player?.closeAllVideo()
  }

  // 视频截图
  capture (winIndex, fileName) {
    return this.player?.setCapture(winIndex, fileName)
  }

  // 实时视频录像
  realRecord (winIndex, fileName) {
    this.recordStartList[winIndex] = !this.recordStartList[winIndex]
    this.player?.realRecord(winIndex, this.recordStartList[winIndex], fileName)
  }

  // 获取选中窗口信息
  getWindowInfo (winIndex) {
    return this.player?.getWindowInfo(winIndex) || {}
  }

  // 设置窗口边框选中样式
  setBorderStyle (color, width) {
    this.player?.setBorderStyle(color, width)
  }

  // 分屏
  splitScreen (winNum, row, col) {
    if (row * col === winNum) {
      this.winNum = winNum

      this.gridStyle.display = 'grid'
      this.gridStyle.gridGap = '2px'
      this.gridStyle['grid-template-rows'] = `repeat(${row}, minmax(0, 1fr))`
      this.gridStyle['grid-template-columns'] = `repeat(${col}, minmax(0, 1fr))`

      this.player?.setSplitScreen(winNum)
    }
  }

  // 全屏
  fullScreen () {
    const dom = document.getElementById(this.id)
    dom.style.cssText = 'position: fixed;top: 0;left: 0;width: 100vw;height: 100vh;z-index: 999;'
  }

  // 退出全屏
  exitScreen () {
    const dom = document.getElementById(this.id)
    dom.style.cssText = ''
  }

  // 获取视频宽度和高度
  getVideoWH (winNum) {
    return this.player?.getVideoWH(winNum)
  }

  // 设置指定窗口视频是否铺满
  setVideoSize (index, isFull) {
    this.player?.setVideoSize(index, isFull)
  }

  // 设置实时录像格式
  setDownloadFileType (type = 1) {
    this.player?.setDownloadFileType(type)
  }

  // 设置视频水印
  setWaterMark (name, left, top, rows, cols) {
    this.player?.setWaterMark(name, left, top, rows, cols)
  }

  // 视频播放
  videoPlay (
    winNum,
    codeType,
    devCode,
    videoTalkUrl,
    devName,
    streamType,
    videoUrl,
    hasAudio,
    subConf,
  ) {
    const options = {
      index: winNum,
      devCode,
      devName,
      streamType,
      url: videoUrl,
      hasAudio,
      subConf,
      codeType,
      videoTalkUrl,
    }

    this.player?.setData(options)
  }

  // 窗口箭头云台的显示隐藏
  showControlPanel (type, visible) {
    this.player?.showControlPanel(visible)
  }

  // 主副码流切换
  setStreamType (winNum, streamType) {
    this.player?.setStreamType(winNum, streamType)
  }

  // 内置云台速度控制
  setCloudSpeed (rowSpeed, colSpeed) {
    this.player?.setCloudSpeed(rowSpeed, colSpeed)
  }

  // 云台控制
  videoControl (devCode, cmd, lspeed, rspeed) {
    this.player?.videoControl(devCode, cmd, lspeed, rspeed)
  }

  // 语音对讲
  videoTalk (winNum) {
    this.player?.setTalk(winNum, true)
  }

  // 关闭视频播放
  videoClose (winNum) {
    this.player?.videoClose(winNum)
  }

  // 关闭所有视频
  closeAllVideo () {
    this.player?.closeAllVideo()
  }

  // 视频代理
  enableProxy () {
  }

  // 录像播放
  recordPlay (winNum, codeType, devCode, devName, recordUrl, type, streamType, playurl, decodeTag, startTime, endTime) {
    const url = type === 0 ? recordUrl : playurl
    const options = {
      index: winNum,
      codeType,
      devCode,
      devName,
      url,
      type,
      streamType,
      decodeTag,
      startTime,
      endTime,
    }

    this.player?.setData(options)
  }

  // 视频播放状态
  getVideoState (winNum) {
    return this.player?.getVideoState(winNum)
  }

  // 录像播放速率/定位控制
  remoteFilePlayControl (winNum, controlType, controlValue) {
    this.player?.remoteFilePlayControl(winNum, controlType, controlValue)
  }
}

export default QifPlayer
